<?php
/**
 * 绩效管理
 * 
 * @author  Lee<a605333742@gmail.com>
 * @time    2016-08-09
 */
namespace Admin\Controller; 

class KpiController extends CommonController{
    /*
     * 构造函数
     * 
     * @return #
     */
    public function _initialize() {
        parent::_initialize();
        $this->db_kpi           =D("Kpi");
        $this->db_kpiTasks      =D("KpiTasks");
        $this->db_userRole      =D("UserRole");
        $this->db_user          =D("User");
        $this->db_kpiBehavier   =D("KpiBehavier");
        $this->db_sec           =D("Section");
        $this->db_excel         =D("Excel");
    }
    
    /*
     * 绩效考核列表
     * 
     * @return #
     */
    public function index(){
        $this->commonIndex();
        $this->display();
    }
    
    /*
     * 任务列表
     * 
     * @return #
     */
    public function takList(){ 
        $map['status']      =1;
        if(I("request.kpi_id")){
            session("kpi_id",I("request.kpi_id",'',"code"));
            $map['kpi_id']  =I("request.kpi_id",'',"code");
        }else{
            $map['kpi_id']  =session("kpi_id");
        }
        $this->_list($this->db_kpiTasks,$map);
        $this->assign("kpi_id",$map['kpi_id']);
        $this->display();
    }
    
    /*
     * show前置操作
     * 
     * @return #
     * 
     */
     
    public function _before_show(){        
        if(I("request.kpi_id")){
            $this->assign("kpi_id",I("request.kpi_id",'',"code"));
        }
    }
    
    /*
     * edit前置操作
     * 
     * @return  #
     */
    public function _before_edit(){
        if(I("request.percentage")){
            $_POST['percentage']    =rtrim(I("request.percentage"),"%").'%';
        }
    }
    
    /*
     * ajax查询用户更改后的部门和职业
     * 
     * @return  #
     */
    public function ajaxUserName(){
        $map['name|nickname']   =trim(I("request.username"));
        $map['status']          =1;
        $user       =$this->db_user->where($map)->find();
        if(!$user){
            echo 1;
            exit;
        }
        if(session("role_id")==5){
            if($user['section_id']!=session("section")){
                echo 2;
                exit;
            }
        }
        $user['sec']=getSection($user['section_id']);
        $this->ajaxReturn($user,'JSON');
    }
    
    /*
     * 绩效考核审核详情
     * 
     * @return #
     */
    public function show_(){
        $map['status']  =1;        
        $map['kpi_id']  =I("request.id",'','code');        
        //kpi任务详情
        $kTInfo =$this->db_kpiTasks->where($map)->order('id',asc)->select();        
        //kpi行为考核详情
        $kBInfos=$this->db_kpiBehavier->where($map)->find();
        $this->assign("kBInfo",$kBInfos);
        $this->assign("kTInfo",$kTInfo);
        $this->assign('kCount',count($kTInfo));        
        //kpi考核详情
        A("Common")->show();
    }
    
    /*
     * 审核
     * 
     * @return #
     */
    public function result(){
        //主要目标考核start
        $tasksCount =$this->db_kpiTasks->where(array("kpi_id"=>I("post.kpi_id")))->count();
        for($i=0;$i<$tasksCount;$i++){
            $map0['id']     =I("request.id".$i);
            $map0['higher_upassessment']=I("request.higher_upassessment".$i);
            $this->db_kpiTasks->save($map0);
        }
        $tasksList  =$this->db_kpiTasks->where(array("kpi_id"=>I("post.kpi_id")))->select();
        $data   =array();
        foreach($tasksList as $vo){
            $data[] =($vo['self_assessment']*0.3+$vo['higher_upassessment']*0.7)*$vo['percentage'];        
        }
        $map2['total_score1']   =sprintf("%.2f",array_sum($data)/100);//主要目标考核总分
        
        if(I("post.behavier_id")){
            $map1['id']                 =I("post.behavier_id");
        }
        if(I("post.kpi_id")){
            $map1['kpi_id']             =I("post.kpi_id");
        }
        if(I("post.h_execution")){
            $map1['h_execution']        =I("post.h_execution");
        }
        if(I("post.h_counseling_skills")){
            $map1['h_counseling_skills']=I("post.h_counseling_skills");
        }
        if(I("post.h_team_work")){
            $map1['h_team_work']        =I("post.h_team_work");
        }
        if(I("post.h_professional")){
            $map1['h_professional']     =I("post.h_professional");
        }
        
        /*kpi之行为考核数据 end*/
        /*kpi之总考核 start*/
        if(I("post.kpi_id")){
            $map2['id']                 =I("post.kpi_id");
        }
        if(I("post.types")){
            $map2['types']              =I("post.types");
        }
        if(isset($_POST['rewards'])){
            $map2['rewards']            =$_POST['rewards'];
        }
        if(isset($_POST['punishment'])){
            $map2['punishment']         =$_POST['punishment'];
        }
        $map2['total_score2']       =sprintf("%.2f",$map1['h_execution']*0.4+$map1['h_counseling_skills']*0.2+$map1['h_team_work']*0.2+$map1['h_professional']*0.2);
        $map2['total_score']        =sprintf("%.2f",$map2['total_score1']*100/5)*0.8+($map2['total_score2']*100/5)*0.2+$map2['rewards']-abs($map2['punishment']);
        $map2['final_score_level']  =getFinalLevel($map2['total_score']);
        $map2['assign_id']          =session("authId");
        $map2['end_time']           =date("Y-m-d H:i:s", time());
        $map2['is_examine']         =1;
        $map2['is_gongbu']          =0;
        $map2['rew_remark']         =I("request.rew_remark");
        $map2['pun_remark']         =I("request.pun_remark");
        if($map1['id']){
            $result1=$this->db_kpiBehavier->save($map1);
        }else{
            $result1=$this->db_kpiBehavier->add($map1);
        }
        $result2    =$this->db_kpi->save($map2);
        if($result1 || $result2){
            if(A("Common")->addLog("审核","id为{$map2['id']}")){
                $data[20]   =$map2['total_score1'];
                $data[21]   =$map2['total_score2'];
                $data[22]   =$map2['total_score'];
                $data[23]   =$map2['final_score_level'];
                $data[24]   =coefficient($map2['total_score']);
                $this->ajaxReturn($data);
            }else{
                echo FALSE;
            }
        }else{
            echo FALSE;
        }
    }
    
    /*
     * 季度统计表
     * 
     * @return #
     */
    public function quarterlyList(){
        $map['end_time']=array('neq','');
        $map['status']  =array('neq',0);
        if(I("request.accept_user")){
            $map['accept_id']   =A("Common")->getIds(I("request.accept_user"),"name","User");
        }
        if($this->checkYQ()){
            $map=array_merge($map,$this->checkYQ());
            $_REQUEST ['listRows']=1000;
        }
        $list   =$this->db_kpi->where($map)->order("section_id ")->select();
        $this->assign("list",$list);
        $this->display();
    }
    
    
    /*
     * 公用查询条件集成
     * 
     * @return #
     */
    public function checkYQ($sign){        
        if(I("request.quarter") && !I("request.year")){
            //季度存在，年份不存在，则为查询当前年的指定季度绩效。当前绩效默认以end_timez作为时间分割
            $map['quarter']     =I("request.quarter");
            if($sign){
                $map['add_time']=array("LIKE","%".date("Y", time())."%");
            }else{
                $map['end_time']=array("LIKE","%".date("Y", time())."%");
            }            
        }else if(I("request.quarter") && I("request.year")){
            $map['quarter']     =I("request.quarter");
            if($sign){
                $map['add_time']=array("LIKE","%".trim(I("request.year"))."%");
            }else{
                $map['end_time']=array("LIKE","%".trim(I("request.year"))."%");
            }
        }else if(!I("request.quarter") && I("request.year")){
            if($sign){
                $map['add_time']=array("LIKE","%".trim(I("request.year"))."%");
            }else{
                $map['end_time']=array("LIKE","%".trim(I("request.year"))."%");
            }
        }
        return $map?$map:'';
    }
    
    
    /*
     * 公布考核
     * 
     * @return #
     */
    public function gongbu(){        
        $map['id']          =array('in', implode(',', I("request.id")));
        $map['is_gongbu']   =1;
        if($this->db_kpi->save($map)){
            $this->success("公布成功");
        }else{
            $this->error("公布失败");
        }
    }
    
    /*
     * 导出为excel
     * 
     * @return #
     */
    public function downexcel(){
        $list   =$this->db_kpi->where(array("id"=>array("in",implode(",",I("request.id")))))->order("section_id ")->select();
        foreach($list as $k=>$v){
            $list[$k]["section"]    =get_User_sec($v['accept_id']);                     //部门
            $list[$k]["username"]   =getUsername($v['accept_id']);                      //用户
            $list[$k]["nickname"]   =getUsername($v['accept_id'],1);                    //英文名
            $list[$k]["board_time"] =getJionDate($v['accept_id']);                      //入职日期
            $list[$k]['_t_score']   =$v['total_score']-$v['rewards']+$v['punishment'];  //实际分数
            $list[$k]['force']      =$v['rewards']-$v['punishment'];                    //强制分数
            $list[$k]['coefficient']=coefficient($v['total_score']);                    //考核系数
        }
        
        import("Org.Util.PHPExcel");
        $objPHPExcel    =new \PHPExcel();
        $objPHPExcel->getProperties()
                    ->setCreator("JAMES")
                    ->setLastModifiedBy("JAMES")
                    ->setTitle("zltrans")
                    ->setSubject("Dorder")
                    ->setDescription("Dorder List")
                    ->setKeywords("Dorder")
                    ->setCategory("Test result file");
        
        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue("A1","部门")
                    ->setCellValue("B1","姓名")
                    ->setCellValue("C1","英文名")
                    ->setCellValue("D1","入职日期")
                    ->setCellValue("E1","实际分数")
                    ->setCellValue("F1","强制分数")
                    ->setCellValue("G1","最终得分")
                    ->setCellValue("H1","等级")
                    ->setCellValue("I1","考核系数")
                    ->setCellValue("J1","备注");
        for($i=0;$i<count($list);$i++){
            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue("A".($i+2),$list[$i]['section'])
                        ->setCellValue("B".($i+2),$list[$i]['username'])
                        ->setCellValue("C".($i+2),$list[$i]['nickname'])
                        ->setCellValue("D".($i+2),$list[$i]['board_time'])
                        ->setCellValue("E".($i+2),$list[$i]['_t_score'])
                        ->setCellValue("F".($i+2),$list[$i]['force'])
                        ->setCellValue("G".($i+2),$list[$i]['total_score'])
                        ->setCellValue("H".($i+2),$list[$i]['final_score_level'])
                        ->setCellValue("I".($i+2),$list[$i]['coefficient']);
        }
        import("Org.Util.PHPExcel.IOFactory");
        $objWritor  = \PHPExcel_IOFactory::createWriter($objPHPExcel,"Excel2007");
        $path       ="Application/Public/Upload/excel/";
        $filename   =time().".xlsx";
        if($objWritor->save($path.$filename)){
            $this->error("转换失败");
        }else{
            $map['name']    =$filename;
            $this->db_excel->add($map);
            $this->success("转换成功");
        }
    }
    
    /*
     * 季度统计excel列表
     * 
     * @return #
     */
    public function excelList(){
        A("Common")->index("Excel");
    }
    
    /*
     * 判断该季度的考核是否设置过
     * 
     * @return bool
     */
    public function ajaxIs_set(){
        if(I("request.quarter")){
            $map['quarter']     =I("request.quarter");
        }
        if(I("request.username")){
            $map['accept_id']   =A("Common")->getIds(I("request.username"),"name","User");
        }        
        $map['status']      =1;
        $map['add_time']    =array("LIKE",date('Y')."%");
        if($this->db_kpi->where($map)->select()){
            echo 1;
        }else{
            echo 2;
        }
    }
    
    /*
     * 显示新增任务项目
     * 
     * @return #
     */
    public function show_s(){
        $this->_before_show();
        $this->display();
    }
    
    /*
     * 处理权重相加必须等于100
     * 
     * @return #
     */
    public function ajaxCount(){
        $tasks  =$this->db_kpiTasks->where(array("kpi_id"=>I("request.kpi_id"),"status"=>1))->select();
        $data   =array();
        foreach($tasks as $vo){
            $data[] =$vo['percentage'];
        }
        $count_ =array_sum($data)+I("request.count_");
        if($count_==100){
            echo 1;
        }else{
            echo 2;
        }
    }
    
    /*
     * 处理新增项目
     * 
     * @return #
     */
    public function edit_(){
        for($i=1;$i<11;$i++){
            if(I("request.subjects".$i)){
                $map['kpi_id']              =I("request.kpi_id");
                $map['db']                  =I("request.db");
                $map['subjects']            =I("request.subjects".$i);
                $map['percentage']          =trim(I("request.percentage".$i),"%").'%';
                $map['modification_record'] =trim(I("request.modification_record".$i));
                if(I("request.completion_data".$i)){
                    $map['completion_data']         =I("request.completion_data".$i);
                }
                if(I("request.actual_completion_data".$i)){
                    $map['actual_completion_data']  =I("request.actual_completion_data".$i);
                }
                $this->db_kpiTasks->add($map);
            }
        }
        $kpi_info   =$this->db_kpi->where(array("id"=>I("request.kpi_id")))->find();
        if($kpi_info && $kpi_info['is_tasks']==0){
            $map1['id']         =I("request.kpi_id");
            $map1['is_tasks']   =1;
            $this->db_kpi->save($map1);
        }
        $this->success("新增成功");
    }
    
    /*
     * 已审核Kpi列表
     * 
     * @return #
     */
    public function endIndex(){
        $sign   =1;        
        $this->commonIndex($sign);
        $this->assign("sign",$sign);
        $this->display("index");
    }
    
    /*
     * 公共的index 
     * 
     * @return #
     */
    public function commonIndex($sign){
        $role_id    =$this->db_userRole->where(array("u_id"=>session("authId")))->getField("role_id");
        session("role_id",$role_id);
        if(I("request.accept_user")){
            $map['accept_id']  =A("Common")->getIds(I("request.accept_user"),"name","User");
        }
        if(I("request.assign_user")){
            $map['assign_id']  =A("Common")->getIds(I("request.assign_user"),"name","User");
        }
        if(I("request.end_time")){
            $map['end_time']   =array("egt",I("request.end_time"));
        }
        if($role_id==5){
            $section    =$this->db_user->where(array("id"=>session("authId")))->getField("section_id");
            session("section",$section);
            $ids        =$this->db_user->where(array("section_id"=>$section))->select();
            
            $data       =array();
            foreach($ids as $vo){
                $data[] =$vo['id'];
            }
            $map['accept_id']   =array("in",implode(",",$data));
            
        }
        if(session("authId")==7){
            $map['accept_id']   =array("in","185,183");
        }
        $map['status']  =1;
        if(!$sign){
            $map['is_examine']  =0;
        }else{
            $map['is_examine']  =1;
        }
        $is_add ='lee';
        if($this->checkYQ($is_add)){
            $map=  array_merge($map,$this->checkYQ($is_add));           
        }
        $this->_list($this->db_kpi,$map,'section_id',TRUE);
    }
    
    /*
     * 显示新增考核
     * 
     * @return #
     */
    public function show_e(){
        if(I("post.")){       
            $map1['status'] =1;
            $map1['id']     =array("neq",1);
            $uids   =$this->db_user->where($map1)->select(array("field"=>"id,section_id"));
            foreach($uids as $vo){
                $map['quarter']     =I("post.quarter");
                $map['accept_id']   =$vo['id'];
                $map['section_id']  =$vo['section_id'];
                if(false === $this->db_kpi->create()){
                    $this->error("绩效考核添加失败");
                    break;
                }
                $this->db_kpi->add($map);
            }
            $this->success("绩效考核添加成功");
        }else{
            $this->display();
        }
    }  
    
    /*
     * 删除前置操作
     * 
     * @return #
     */
    public function _before_del(){
        if(!I("request.db")){
            if(!is_array(I("request.id"))){                
                $id =explode(",",code(I("request.id")));                
            }else{
                $id =I("request.id"); 
            } 
            if($this->db_kpiTasks->where(array("kpi_id"=>array('in', implode(',', $id))))->select()){
                $this->db_kpiTasks->where(array("kpi_id"=>array('in', implode(',', $id))))->save(array("status"=>0));                
            }
            if($this->db_kpiBehavier->where(array("kpi_id"=>array('in', implode(',', $id))))->select()){
                $this->db_kpiBehavier->where(array("kpi_id"=>array('in', implode(',', $id))))->save(array("status"=>0));
            }
        }
    }
}